//
//  AlbumViewController.m
//  myCar
//
//  Created by 王子洁 on 14/10/30.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "AlbumViewController.h"
#import "UIImageView+WebCache.h"
#import "AFHTTPRequestOperationManager.h"
#import "AutoScrollView.h"
#import "AlbumCollectionViewCell.h"
#import <Comment/Comment.h>
#import "WebColor.h"
#import "MBProgressHUD.h"
@interface AlbumViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate, UIAlertViewDelegate>

@property (nonatomic, retain)UIView *myView;

@property (nonatomic, retain)NSMutableArray *imageArr;

@property (nonatomic, retain)UICollectionView *collectionView;

@property (nonatomic, retain)UILabel *pageNo;

@property (nonatomic, assign)int page;

@property (nonatomic, retain)NSString *url;

@end

@implementation AlbumViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.imageArr = [NSMutableArray array];
        
    }
    return self;
}

- (void)dealloc
{
    [_imageArr release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    self.tabBarController.tabBar.hidden = YES;
  
    
    [self addMyView];
    [self setNav];
    [self initCollectionView];
    [self reloadData];
    [self setSaveButton];
    [self setPageNo];

}


- (void)setSaveButton
{
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeSystem];
    saveButton.backgroundColor = [UIColor blackColor];
    saveButton.tintColor = [UIColor whiteColor];
    saveButton.frame = CGRectMake(20, self.view.bounds.size.height - 110, 25, 25);
    
    [saveButton addTarget:self action:@selector(buttonSave:) forControlEvents:UIControlEventTouchUpInside];
    [saveButton setBackgroundImage:[UIImage imageNamed:@"xiazai.png"] forState:UIControlStateNormal];
    [self.view addSubview:saveButton];
}

-(void)setPageNo
{
    self.pageNo = [[UILabel alloc] initWithFrame:CGRectMake(250, self.view.bounds.size.height - 115, 50, 35)];
    self.pageNo.backgroundColor = [UIColor blackColor];
    self.pageNo.textColor = [UIColor whiteColor];
    [self.view addSubview:self.pageNo];
    [_pageNo release];
}

- (void)reloadData
{
    NSString *str = [NSString stringWithFormat:@"http://agent1.pconline.com.cn:8941/pcautophoto/iphone_json.jsp?id=%@", self.info.number];
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager1 GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableArray *arr = [responseObject objectForKey:@"photos"];
        for (NSDictionary *dic in arr) {
            Information *info = [[Information alloc] init];
            info.title = [dic valueForKey:@"name"];
            info.url = [dic valueForKey:@"url"];
            info.content = [dic valueForKey:@"desc"];
            [self.imageArr addObject:info];
            [info release];
        }
    
        [self.collectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请返回" delegate:self cancelButtonTitle:@"请返回" otherButtonTitles:nil, nil];
        alertView.tag = 1200;
        [alertView show];
        [alertView release];
    }];
    
    
}

- (void)initCollectionView
{
    // 首页信息
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 调整cell的大小
    flowLayout.itemSize = CGSizeMake(320, 380);
    // 调整滚动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // cell行之间的间距
    flowLayout.minimumLineSpacing = 0;
 
    self.collectionView =[[UICollectionView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 7, self.view.frame.size.width, self.view.frame.size.height / 7 * 6 - 120) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor blackColor];
    // 禁用collectionView的滚动效果
    self.collectionView.scrollEnabled = YES;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[AlbumCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [flowLayout release];
    [_collectionView release];

}

- (void)setNav
{
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(goBack:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share.png"] style:UIBarButtonItemStylePlain target:self action:@selector(share:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
}

- (void)addMyView
{
    self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
    self.myView.backgroundColor = [UIColor blackColor];
    [self.navigationController.navigationBar addSubview:self.myView];
    [_myView release];

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSString *str = [NSString stringWithFormat:@"1/%lu", (unsigned long)self.imageArr.count];
    self.pageNo.text = str;
    return self.imageArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    AlbumCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    Information *info = [self.imageArr objectAtIndex:indexPath.item];
    [cell.myImage setImageWithURL:[NSURL URLWithString:info.url]];
   
    
    if ([info.content isEqualToString:@""]) {
        cell.myLabel.text = info.title;
        [cell.myLabel sizeToFit];
    } else {
        cell.myLabel.text = info.content;
        [cell.myLabel sizeToFit];
    }
    cell.myLabel.frame = CGRectMake(10, 10, self.view.bounds.size.width - 20, cell.myLabel.bounds.size.height);
    
    cell.myScrollView.contentSize = CGSizeMake(0, cell.myLabel.frame.size.height + 20);

    return cell;
}

- (void)goBack:(UIBarButtonItem *)button
{
//    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor  = [WebColor white];
    [self.myView removeFromSuperview];
    CATransition *animation = [CATransition animation];
    
    [animation setDuration:0.3];
    
    [animation setType: kCATransitionMoveIn];
    
    [animation setSubtype: kCATransitionFromBottom];
    
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    
    [self.navigationController.view.layer addAnimation:animation forKey:nil];
    [self.navigationController popViewControllerAnimated:NO];

}

- (void)share:(UIBarButtonItem *)button
{
    NSLog(@"self.page %d", self.page);
    Information *info = [self.imageArr objectAtIndex:self.page];
    NSString *str = [NSString stringWithFormat:@"%@ %@", info.title, info.url];
    
    id<ISSContent> content = [ShareSDK content:str defaultContent:@"要分享的内容为空时" image:nil title:@"share" url:@"http://www.baidu.com" description:@"这是描述" mediaType:SSPublishContentMediaTypeNews];
    
    [ShareSDK showShareActionSheet:nil shareList:nil content:content statusBarTips:YES authOptions:nil shareOptions:nil result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
        [self.view addSubview:alertView];
        if (state == SSResponseStateSuccess) {
            NSLog(@"分享成功");
            [alertView setTitle:@"分享成功"];
            [alertView show];
        } else if (state == SSResponseStateFail) {
            NSLog(@"分享失败");
            [alertView setTitle:@"分享失败"];
            [alertView show];
        }
    }];

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.collectionView) {
        float a = self.collectionView.contentOffset.x / self.view.bounds.size.width + 1;
        NSLog(@"nihao%f", a);
        NSString *str = [NSString stringWithFormat:@"%.f/%lu", a, (unsigned long)self.imageArr.count];
        self.pageNo.text = str;
        self.page = a - 1;
    }
       
}

- (void)buttonSave:(UIButton *)button
{
    
    UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"确定下载吗" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确定", nil];
    [view show];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIAlertView *alert = (UIAlertView *)[alertView viewWithTag:1200];
    if (alertView == alert) {
        if (buttonIndex == 0) {
            self.navigationController.navigationBar.tintColor  = [WebColor white];
            [self.myView removeFromSuperview];
            CATransition *animation = [CATransition animation];
            
            [animation setDuration:0.3];
            
            [animation setType: kCATransitionMoveIn];
            
            [animation setSubtype: kCATransitionFromBottom];
            
            [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
            
            [self.navigationController.view.layer addAnimation:animation forKey:nil];
            [self.navigationController popViewControllerAnimated:NO];
        }
    } else
    if (buttonIndex == 1) {
        Information *info = [self.imageArr objectAtIndex:self.page];
        UIImageView *imageView = [[UIImageView alloc] init];
        [imageView setImageWithURL:[NSURL URLWithString:info.url]];
        UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(imageSaveToPhotosAlbum:didFishSavingWithError:contentInfo:), nil);
        [imageView release];
    } else {
    
    }
}

- (void)imageSaveToPhotosAlbum:(UIImage *)image didFishSavingWithError:(NSError *)error contentInfo:(void *)contextInfo
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"成功保存到相册" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
    if (!error) {
        [alertView setTitle:@"已保存"];
      
    } else {
        [alertView setTitle:@"保存失败"];
    }
    [alertView show];
    [self.view addSubview:alertView];
    
}



- (void)viewWillDisappear: (BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
